import pandas as pd
import os
import numpy as np


def excel_to_json(filename):
    print(f"开始转换excel_to_json {filename}")

    # 创建 'jsons' 目录（如果不存在）
    jsons_dir = 'assets/locales'
    if not os.path.exists(jsons_dir):
        os.makedirs(jsons_dir)

    # 读取Excel文件，确保包含key、简体、繁体列
    try:
        df = pd.read_excel(filename, usecols=['key','简体', '繁体'], na_filter=False)
    except Exception as e:
        print(f"读取Excel文件失败: {e}")
        return

    # 将空字符串替换为NaN
    df.replace("", np.nan, inplace=True)

    # 删除'key'列中的空值
    df = df.dropna(subset=['key'])

    print("Excel数据预览:")
    print(df.head())

    # 将'key'列设置为索引
    df.set_index('key', inplace=True)

    # 移除重复的索引行
    df = df[~df.index.duplicated(keep='first')]

    # 生成zh.json (简体中文)
    try:
        formatted_json_zh = df['简体'].to_json(indent=2, force_ascii=False)
        
        with open(os.path.join(jsons_dir, 'zh_CN.json'), 'w', encoding='utf-8') as json_file:
            json_file.write(formatted_json_zh)
        
        print(f"简体中文转换成功！文件路径：{os.path.abspath(os.path.join(jsons_dir, 'zh_CN.json'))}")
    except Exception as e:
        print(f"生成简体中文文件失败: {e}")

    # 生成zh_TW.json (繁体中文)
    try:
        formatted_json_hk = df['繁体'].to_json(indent=2, force_ascii=False)
        
        with open(os.path.join(jsons_dir, 'zh_TW.json'), 'w', encoding='utf-8') as json_file:
            json_file.write(formatted_json_hk)
        
        print(f"繁体中文转换成功！文件路径：{os.path.abspath(os.path.join(jsons_dir, 'zh_TW.json'))}")
    except Exception as e:
        print(f"生成繁体中文文件失败: {e}")



# Example Usage:
# 请将 'example.xlsx' 替换为你的实际 Excel 文件路径

# 获取当前脚本所在目录
script_directory = os.path.dirname(os.path.abspath(__file__))

# 拼接 Excel 文件的绝对路径
excel_file_path = os.path.join(script_directory, '09game.xlsx')

# Example Usage:
excel_to_json(excel_file_path)
